<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Description of admin_helper
 *
 * @author Admin
 */


/**
 * Kiem tra user da dang nhap hay chua
 * 
 * @return boolean
 */
function user_is_login()
{
    $CI = & get_instance();
    $CI->load->model('model_user');
    
    // Kiem tra session
    $user_id = $CI->session->userdata('user_id');
    //echo $user_id;die();
    if(!$user_id){
        $user_id = user_check_cookie();
        if(!$user_id) return false;
    }
    $info = $CI->model_user->get_info($user_id);
    if(!$info) return false;
    return true;
}

/**
 * Kiem tra dang nhap user tren cookie
 * @return user
 */
function user_check_cookie()
{
    $CI = & get_instance();
    $CI->load->model('model_user');
    
    $username = $CI->input->cookie('username');
    $password = $CI->input->cookie('password');
    
    return user_login($username, $password, true, false);
    
}

/**
 * Dang nhap 
 * @param string $username
 * @param string $password
 * @param boolean $remember
 * @param boolean $md5
 * @return user
 */
function user_login($username, $password, $remember, $md5 = true)
{
	if($username=='' || $password =='') return false;
    $CI = & get_instance();
    $CI->load->model('model_user');
    
    $password = $md5?md5($password):$password;
    $where = array(
        'username'  => $username,
        'password'  => $password,
    );
    
    $user = $CI->model_user->get_info_rule($where);
    
    if(!$user) return false;
	
	if($user->id==$CI->config->item('root_admin')) 
		$CI->session->set_userdata(array('root_admin'=>true));
	else if($user->active==0) return false;
	
    $CI->session->set_userdata(array('user_id'  => $user->id));
    if($remember){
		//echo 'save cookie';die();
        set_cookie('username',$username);
        set_cookie('password',$password);
    }
    return $user;
}

/**
 * 
 * @return array
 */
function user_get_permission()
{
    if(!user_is_login()) return array();
    $CI = &get_instance();
	$CI->load->model('model_user');
	$CI->load->model('model_group');
	$user_id = $CI->session->userdata('user_id');
	$user = $CI->model_user->get_info($user_id);
	$group = $CI->model_group->get_info($user->group_id);
	return json_decode($group->permissions);
}

?>
